<script>
import addtable from '@/mixins/addtable'
import fieldConfig from '../fieldConfig.vue'
import DialogForm from '@/components/DialogForm'
import AjaxStore from '@/utils/store/proxyAjax'
import request from '@/utils/request'
import store from './store'
import WrapTable from '@/components/WrapTable'
import SearchForm from '@/components/SearchForm'
import ButtonList from '@/components/ButtonList'
import TableButtonList from '@/components/TableButtonList'

export default {
  name: 'tableFieldAuth',
  mixins: [addtable, store],
  props: {
    datagroupId: {
      type: String,
      default: ''
    },
    datagroupName: {
      type: String,
      default: ''
    }
  },
  components: {
    DialogForm,
    fieldConfig,
    WrapTable,
    SearchForm,
    ButtonList,
    TableButtonList
  },
  data() {
    return {
      userIds: [],
      tableId: '',
      tableName: '',
      dialogType: '',
      tableConfigId: '',
      selectedList: [],
      showInputFlag: false,
      tableIndexCol: true,
      tableSelectionCol: true,
      allFields: [],
      defaultItemsLength: 5,

      tableOptWidth: '80',
      idKey: 'tableConfigId',
      delIdKey: 'tableConfigIds',
      delListIdKey: 'tableConfigIds',

      delUrl: '/v1/yq/datagroup/deleteTable',
      delListUrl: '/v1/yq/datagroup/deleteTable',
      getAllFieldUrl: '/v1/yq/datagroup/getFieldByTableId',
      addFieldConfigUrl: '/v1/yq/datagroup/addFieldConfig',
      store: new AjaxStore({
        url: '/v1/yq/datagroup/queryAssignedTableList'
      }),
      columns: [
        {
          prop: 'tableName',
          label: '表',
          sortable: true,
          'header-align': 'center',
          'min-width': '120',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'tableEname',
          label: '英文表名',
          sortable: true,
          'header-align': 'center',
          'min-width': '120',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'dbName',
          label: '数据源',
          sortable: true,
          'header-align': 'center',
          'min-width': '120',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'firstName',
          label: '一级分类',
          sortable: true,
          'header-align': 'center',
          'min-width': '120',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'secondName',
          label: '二级分类',
          sortable: true,
          'header-align': 'center',
          'min-width': '120',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'fieldName',
          label: '授予字段',
          sortable: true,
          'header-align': 'center',
          'min-width': '240',
          'show-overflow-tooltip': true,
          align: 'center'
        },
        {
          prop: 'scale',
          label: '已授权字段数/总字段数',
          sortable: true,
          'header-align': 'center',
          'min-width': '200',
          'show-overflow-tooltip': true,
          align: 'center'
        }
      ],
      searchFields: [
        {
          label: '数据源',
          prop: 'dbId',
          placeholder: '请选择数据源',
          xType: 'SelectConfig',
          isLocal: false,
          relatedFields: ['firstCateId', 'secondCateId'],
          anchor: 8,
          getData: () => {
            return request({
              url: '/v1/yq/datagroup/getDbList',
              method: 'get'
            }).then(({ data }) => {
              return data.map(item => {
                return {
                  value: /^\d+$/.test(item.objId)
                    ? parseInt(item.objId)
                    : item.objId + '',
                  label: item.dbName,
                  ...item
                }
              })
            })
          }
        },
        {
          label: '一级分类',
          prop: 'firstCateId',
          placeholder: '请选择一级分类',
          xType: 'SelectConfig',
          isLocal: false,
          autoLoad: false,
          relatedFields: ['secondCateId'],
          ref: 'firstCateId',
          anchor: 8,
          on: {
            'el.form.update': (val, ctx, origin, form) => {
              form.model.firstCateId = ''
              ctx.load({ dbId: form.model.dbId })
            }
          },
          getData: params => {
            if (params && params.dbId) {
              return request({
                url: '/v1/yq/datagroup/getCateList',
                method: 'get',
                params: params
              }).then(({ data }) => {
                return data.map(item => {
                  return {
                    value: /^\d+$/.test(item.objId)
                      ? parseInt(item.objId)
                      : item.objId + '',
                    label: item.cateName,
                    ...item
                  }
                })
              })
            } else {
              return Promise.resolve([])
            }
          }
        },
        {
          label: '二级分类',
          prop: 'secondCateId',
          placeholder: '请选择二级分类',
          xType: 'SelectConfig',
          isLocal: false,
          autoLoad: false,
          ref: 'secondCateId',
          anchor: 8,
          on: {
            'el.form.update': (val, ctx, origin, form) => {
              form.model.secondCateId = ''
              ctx.load({ dbId: form.model.dbId, pid: form.model.firstCateId })
            }
          },
          getData: params => {
            if (params && params.dbId && params.pid) {
              return request({
                url: '/v1/yq/datagroup/getCateList',
                method: 'get',
                params: params
              }).then(({ data }) => {
                return data.map(item => {
                  return {
                    value: /^\d+$/.test(item.objId)
                      ? parseInt(item.objId)
                      : item.objId + '',
                    label: item.cateName,
                    ...item
                  }
                })
              })
            } else {
              return Promise.resolve([])
            }
          }
        },
        {
          label: '表名称',
          prop: 'tableName',
          placeholder: '请输入表名称',
          anchor: 8
        },
        {
          label: '英文表名称',
          prop: 'tableEname',
          placeholder: '请输入英文表名称',
          anchor: 10
        }
      ],
      searchModel: {
        dbId: '',
        firstCateId: '',
        secondCateId: '',
        tableName: '',
        tableEname: ''
      },

      searchBtnList: this.searchBtns,
      toolPanelBtnList: this.toolPanelBtns,
      tableRowBtnList: this.tableRowBtns,
      submitBtnList: this.submitBtns
    }
  },
  methods: {
    getData({ page, limit }) {
      this.store && (this.store._searchParams.datagroupId = this.datagroupId)
      this.store.read({ start: page, limit: limit })
    },
    handleSearch(data, _form) {
      if (data) {
        for (const k in data) {
          if (data.hasOwnProperty(k)) {
            this.store._searchParams[k] = data[k]
          }
        }
        this.$refs.table.load(1, this.store.limit)
      }
    },
    handleDelGroup() {
      if (this.selectedList.length === 0) {
        this.$message({
          type: 'info',
          message: '没有要删除的数据'
        })
        return Promise.reject(new Error('没有要删除的数据'))
      }
      const funIds = this.selectedList
        .map(item => {
          return item[this.idKey]
        })
        .join(',')
      return this.$confirm(
        '此操作不能回退，确认要删除您选中的数据么?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      )
        .then(() => {
          const params = {}
          params[this.delListIdKey] = funIds
          params.datagroupId = this.datagroupId
          return this.delList(params)
        })
        .then(({ success, message }) => {
          this.$message({
            customClass: 'datagroup-message',
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load(1)
            this.$refs.table.clearSelection()
          }
        })
        .catch(error => {
          this.$message({
            customClass: 'datagroup-message',
            type: 'info',
            message: error === 'cancel' ? '已取消删除' : error
          })
          return Promise.reject(error)
        })
    },
    handleDelete(row) {
      return this.$confirm(
        '此操作不能回退，确认要删除您选中的数据么?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      )
        .then(() => {
          const params = {}
          params[this.delIdKey] = row[this.idKey]
          params.datagroupId = this.datagroupId
          return this.del(params)
        })
        .then(({ success, message }) => {
          this.$message({
            customClass: 'datagroup-message',
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load(1)
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            customClass: 'datagroup-message',
            type: error === 'cancel' ? 'info' : 'error',
            message:
              error === 'cancel'
                ? '已取消删除'
                : error instanceof Error
                ? error.message
                : error
          })
          // return Promise.reject(error)
        })
    },
    handleFieldConfig(row) {
      this.getAllField({ q_tableId: row.tableid, start: 1, limit: 99999999 })
        .then(({ success, data }) => {
          if (success) {
            this.allFields = data
            if (row.fieldid) {
              const fieldid = row.fieldid.split(',').map(item => {
                return item
              })
              this.userIds = fieldid.map(items => {
                return data.filter(item => {
                  return item.ename === items
                })[0]
              })
            }
            this.tableId = row.tableid
            this.tableConfigId = row.tableConfigId
            this.tableName = row.tablename
            this.dialogType = 'fieldConfig'
          } else {
            this.$message({
              customClass: 'datagroup-message',
              type: 'error',
              message: '获取表内所有字段失败！'
            })
          }
        })
        .catch(err => console.log(err))
    },
    handleAddFieldConfig() {
      const selectField = this.$refs.fieldConfig.handleReturnSelectedList()
      const params = {}
      params.fields = selectField
        .map(item => {
          return item.ename
        })
        .join(',')
      params.datagroupId = this.datagroupId
      params.tableConfigId = this.tableConfigId
      this.$refs.addFieldConfigBtns.handleChangeStatus('handleAddFieldConfig', {
        loading: true,
        icon: ''
      })
      this.addFieldConfig(params)
        .then(({ success, message }) => {
          this.$message({
            customClass: 'datagroup-message',
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.handleCancel()
            this.$refs.table.load(1)
          }
          this.$refs.addFieldConfigBtns.handleChangeStatus(
            'handleAddFieldConfig',
            { loading: false, icon: '' }
          )
        })
        .catch(err => console.log(err))
    },
    handleCancel() {
      this.$refs.fieldConfig.handleEmptySelectedList()
      this.userIds = []
      this.tableId = ''
      this.tableConfigId = ''
      this.tableName = ''
      this.dialogType = ''
    },
    handleCurrentChange() {
      // 去掉无用弹框
    },
    // eslint-disable-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='table'
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          selectionCol={this.tableSelectionCol}
          indexCol={this.tableIndexCol}
          pagination={this.pagination}
          autoLoad={this.autoLoad}
          tooltip-effect='dark'
          border
          stripe
          default-sort={this.tableDefaultSort}
          on-selection-change={this.handleSelectionChange}
          on-row-dblclick={this.handleCurrentChange}>
          {this.searchBtnList && this.searchBtnList.length > 0 ? (
            <SearchForm
              defaultItemsLength={this.defaultItemsLength}
              items={this.searchFields}
              props-model={this.searchModel}
              slot='searchPanel'
              ref='searchForm'>
              <ButtonList
                operateBtnList={this.searchBtnList}
                props-model={this.searchModel}></ButtonList>
            </SearchForm>
          ) : (
            ''
          )}

          <c-row slot='toolPanel' class='toolPanel'>
            <c-col
              span={this.btnListWidthPercent}
              offset={this.btnListWidthOffset}>
              <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
            </c-col>
            <c-col
              span={this.searchInputWidthPercent}
              justify='end'
              offset={this.searchInputWidthOffset}>
              {this.showInputFlag ? (
                <c-input
                  class='search-input'
                  placeholder={this.inputPlaceholder}
                  size='small'
                  on-input={event => {
                    this.searchInput = event
                  }}
                  nativeOnKeydown={ev => {
                    ev.keyCode === 13
                      ? this.handleInputClick(ev, this.searchInput)
                      : null
                  }}>
                  <i
                    slot='suffix'
                    class='el-input__icon el-icon-search'
                    on-click={ev =>
                      this.handleInputClick(ev, this.searchInput)
                    }></i>
                </c-input>
              ) : (
                ''
              )}
            </c-col>
          </c-row>

          {this.haveTool ? (
            <c-table-column
              label='操作'
              align='center'
              slot='toolbar'
              fixed='right'
              width={this.tableOptWidth}
              {...{
                scopedSlots: {
                  default: scope => {
                    return (
                      <TableButtonList
                        operateBtnList={this.tableRowBtnList}
                        props-model={scope.row}
                      />
                    )
                  }
                }
              }}
            />
          ) : (
            ''
          )}
        </WrapTable>
      )
    },
    // eslint-disable-next-line
    renderCustom(h) {
      return (
        <DialogForm
          closeOnClickModal={false}
          width='720px'
          class='fieldConfig-dialog'
          appendToBody={true}
          visible={this.dialogType === 'fieldConfig'}
          title={`数据组${this.datagroupName}的${this.tableName}表字段权限配置`}
          on-close={this.handleCancel}>
          <fieldConfig
            ref='fieldConfig'
            allFields={this.allFields}
            tableId={this.tableId}
            userIds={this.userIds}
          />
          <c-form ref='form' slot='footer'>
            <c-form-item class='submit-btn'>
              <ButtonList
                ref='addFieldConfigBtns'
                operateBtnList={this.submitBtnList}></ButtonList>
            </c-form-item>
          </c-form>
        </DialogForm>
      )
    }
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.searchBtns = [
      {
        label: '查询',
        methods: 'handleSearch',
        url: '/v1/yq/datagroup/queryAssignedTableList',
        icon: 'el-icon-search',
        type: 'primary',
        disabled: false
      }
      // { label: '重置', methods: 'handleSearchReset', url: '', icon: 'el-icon-refresh', type: 'warning', disabled: false }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.toolPanelBtns = [
      {
        label: '删除',
        methods: 'handleDelGroup',
        url: '/v1/yq/datagroup/deleteTable',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => item.url && urlArr.includes(item.url))

    this.tableRowBtns = [
      {
        label: '字段配置',
        methods: 'handleFieldConfig',
        url: '/v1/yq/datagroup/addFieldConfig',
        svgIcon: 'mdtjconfig',
        icon: '',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '删除',
        methods: 'handleDelete',
        url: '/v1/yq/datagroup/deleteTable',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.submitBtns = [
      {
        label: '保存',
        methods: 'handleAddFieldConfig',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        icon: 'el-icon-circle-close-outline',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)
  }
}
</script>

<style lang="scss">
.tableFieldAuth {
  .searchPanel {
    padding-bottom: 0;
    .search-btn-box {
      bottom: 0;
    }
  }
}
.el-tooltip__popper {
  max-width: 500px;
  word-wrap: break-word;
}
</style>
